package com.usian.app.gateway.filter;


import com.usian.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Log4j2  // 失败需要记录日志
public class AuthorizeFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求对象以及响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 放行登录路径  /admin/api/v1/login/in
        if (request.getURI().getPath().contains("/user/api/v1/login/in")) {
            return chain.filter(exchange);
        }
        // 拦截 鉴权（跟前端约定好，token用什么方式传递？ --》 hearder方式）
        // 在头中获取token
        HttpHeaders httpHeaders = request.getHeaders();
        String token = httpHeaders.getFirst("token");
        if (token == null || "".equals(token)) {
            // 获取cookie
            // queryparam
            log.info("token:{} ","空的");
            // 拦截 返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 解析token
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int result = AppJwtUtil.verifyToken(claims);
            if (result > 0 || result < -1) {
                // 如果失败  直接相应 401 认证错误
                log.info("token:{} ","空的");
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            // 如果成功 token放到请求头中  放行
            // 转发token
            request.mutate().header("token", token);
            return chain.filter(exchange);
        } catch (Exception e) {
            //失败
            log.info("token:{} ","空的");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
